package com.openspring.framework.util;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public class JacksonUtils {

	/**
	 * 将Object转成JSON输出
	 * @param writer
	 * @param obj
	 */
	public static void writerJson(Writer writer, Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        try {
			mapper.writeValue(writer, ObjectUtils.parseNull(obj));
		} catch (JsonGenerationException e) {
			throw new RuntimeException(e);
		} catch (JsonMappingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 将Object转成JSON输出
	 * @param out
	 * @param obj
	 */
	public static void writerJson(OutputStream out, Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        try {
			mapper.writeValue(out, ObjectUtils.parseNull(obj));
		} catch (JsonGenerationException e) {
			throw new RuntimeException(e);
		} catch (JsonMappingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 将JSON格式的字符串转成对象
	 * @param content
	 * @param ref
	 * @return
	 */
	public static <T> T readValue(String content, TypeReference<T> ref) {
		if(StringUtils.isTrimEmpty(content)) {
			return null;
		}
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(StringUtils.parseNull(content), ref);
		} catch (JsonParseException e) {
			throw new RuntimeException(e);
		} catch (JsonMappingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 将JSON格式的字符串转成对象
	 * @param content
	 * @param ref
	 * @return
	 */
	public static <T> T readValue(String content) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(content, new TypeReference<T>() {});
		} catch (JsonParseException e) {
			throw new RuntimeException(e);
		} catch (JsonMappingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
